<!-- eslint-disable vue/no-deprecated-slot-attribute -->
<!-- eslint-disable vue/no-deprecated-slot-scope-attribute -->
<!-- eslint-disable vue/no-deprecated-v-bind-sync -->
<!-- eslint-disable no-unused-vars -->
<template>
  <div class="user-management-container">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 用户列表 -->
    <el-card class="content-card">
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
          <el-button type="primary" @click="openAddDialog" style="margin-left: 700px">添加用户</el-button>
        </div>
      </template>

<!--      &lt;!&ndash; 搜索区域 &ndash;&gt;-->
<!--      <el-row :gutter="20" class="search-area">-->
<!--        <el-col :span="6">-->
<!--          <el-input placeholder="请输入用户名" v-model="queryParams.username" clearable @keyup.enter="searchUser">-->
<!--            <template #append>-->
<!--              <el-button :icon="Search" @click="searchUser"></el-button>-->
<!--            </template>-->
<!--          </el-input>-->
<!--        </el-col>-->
<!--        <el-col :span="6">-->
<!--          <el-input placeholder="请输入手机号" v-model="queryParams.phone" clearable @keyup.enter="searchUser">-->
<!--            <template #append>-->
<!--              <el-button :icon="Search" @click="searchUser"></el-button>-->
<!--            </template>-->
<!--          </el-input>-->
<!--        </el-col>-->
<!--        <el-col :span="6">-->
<!--          <el-select v-model="queryParams.role" placeholder="用户角色" clearable style="width: 100%">-->
<!--            <el-option label="管理员" value="ADMIN"></el-option>-->
<!--            <el-option label="种植户" value="FARMER"></el-option>-->
<!--            <el-option label="经销商" value="DEALER"></el-option>-->
<!--            <el-option label="普通用户" value="CUSTOMER"></el-option>-->
<!--          </el-select>-->
<!--        </el-col>-->
<!--        <el-col :span="6">-->
<!--          <el-button type="primary" @click="searchUser">搜索</el-button>-->
<!--          <el-button @click="resetQuery">重置</el-button>-->
<!--        </el-col>-->
<!--      </el-row>-->

      <!-- 表格 -->
      <el-table :data="userList" border stripe style="width: 100%" v-loading="loading">
        <el-table-column type="index" label="#" width="50"></el-table-column>
        <el-table-column prop="username" label="用户名" width="120"></el-table-column>
        <el-table-column prop="realName" label="真实姓名" width="120">
          <template #default="scope">
            {{ scope.row.realName || '未设置' }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号码" width="120">
          <template #default="scope">
            {{ scope.row.phone || '未设置' }}
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="roleText" label="角色" width="100">
          <template #default="scope">
            <el-tag :type="getRoleTagType(scope.row.role)">{{ scope.row.roleText }}</el-tag>
          </template>
        </el-table-column>
<!--        <el-table-column prop="isActive" label="状态" width="80">-->
<!--          <template #default="scope">-->
<!--            <el-switch-->
<!--              v-model="scope.row.isActive"-->
<!--              active-color="#13ce66"-->
<!--              inactive-color="#ff4949"-->
<!--              @change="() => handleStatusChange(scope.row)">-->
<!--            </el-switch>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column label="操作" width="240">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
            <el-button type="warning" size="small" @click="handleResetPwd(scope.row)">重置密码</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="50%"
      @close="resetForm"
      :close-on-click-modal="false"
    >
      <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userForm.username" placeholder="请输入用户名" :disabled="userForm.id !== null"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="userForm.realName" placeholder="请输入真实姓名"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="userForm.phone" placeholder="请输入手机号码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户角色" prop="role">
              <el-select v-model="userForm.role" placeholder="请选择用户角色" style="width: 100%">
                <el-option label="管理员" value="ADMIN"></el-option>
                <el-option label="生产商" value="FARMER"></el-option>
                <el-option label="经销商" value="DEALER"></el-option>
<!--                <el-option label="普通用户" value="CUSTOMER"></el-option>-->
              </el-select>
            </el-form-item>
          </el-col>
<!--          <el-col :span="12">-->
<!--            <el-form-item label="状态" prop="isActive">-->
<!--              <el-switch-->
<!--                v-model="userForm.isActive"-->
<!--                active-text="启用"-->
<!--                inactive-text="禁用">-->
<!--              </el-switch>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-row>

        <el-form-item label="密码" prop="password" v-if="userForm.id === null">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码"></el-input>
          <div class="form-tip">密码长度不少于6位，包含字母和数字</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog
      title="重置密码"
      v-model="resetPwdDialogVisible"
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form :model="resetPwdForm" :rules="resetPwdRules" ref="resetPwdFormRef" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="resetPwdForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="resetPwdForm.newPassword" type="password" placeholder="请输入新密码"></el-input>
          <div class="form-tip">密码长度不少于6位，包含字母和数字</div>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="resetPwdForm.confirmPassword" type="password" placeholder="请再次输入新密码"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetPwdDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitResetPwd">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, toRefs, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import axios from 'axios';

// 创建API服务
const api = {
  // 获取用户列表
  getUserList(params) {
    return axios.get('/api/users', { params });
  },
  // 获取用户详情
  getUserDetail(id) {
    return axios.get(`/api/users/${id}`);
  },
  // 添加用户
  addUser(data) {
    return axios.post('/api/users', data);
  },
  // 更新用户
  updateUser(id, data) {
    return axios.put(`/api/users/${id}`, data);
  },
  // 删除用户
  deleteUser(id) {
    return axios.delete(`/api/users/${id}`);
  },
  // 更新用户状态
  updateUserStatus(id, status) {
    return axios.patch(`/api/users/${id}/status`, { isActive: status });
  },
  // 重置密码
  resetPassword(id, password) {
    return axios.patch(`/api/users/${id}/password`, { password });
  }
};

export default {
  name: 'UserManagement',
  components: {},
  setup() {
    // 状态
    const state = reactive({
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        username: '',
        phone: '',
        role: ''
      },
      // 总记录数
      total: 0,
      // 用户列表
      userList: [],
      // 对话框显示状态
      dialogVisible: false,
      // 对话框标题
      dialogTitle: '添加用户',
      // 重置密码对话框显示状态
      resetPwdDialogVisible: false,
      // 加载状态
      loading: false
    });

    // 表单引用
    const userFormRef = ref(null);
    const resetPwdFormRef = ref(null);

    // 用户表单
    const userForm = reactive({
      id: null,
      username: '',
      realName: '',
      phone: '',
      email: '',
      role: '',
      isActive: true,
      password: ''
    });

    // 重置密码表单
    const resetPwdForm = reactive({
      userId: null,
      username: '',
      newPassword: '',
      confirmPassword: ''
    });

    // 表单校验规则
    const userRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      realName: [
        { required: false, max: 50, message: '长度不能超过 50 个字符', trigger: 'blur' }
      ],
      phone: [
        { required: false, pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      email: [
        { required: false, type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      role: [
        { required: true, message: '请选择用户角色', trigger: 'change' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能小于6位', trigger: 'blur' },
        { pattern: /^(?=.*[a-zA-Z])(?=.*\d).+$/, message: '密码必须包含字母和数字', trigger: 'blur' }
      ]
    };

    // 重置密码表单校验规则
    const resetPwdRules = {
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能小于6位', trigger: 'blur' },
        { pattern: /^(?=.*[a-zA-Z])(?=.*\d).+$/, message: '密码必须包含字母和数字', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请再次输入新密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== resetPwdForm.newPassword) {
              callback(new Error('两次输入密码不一致'));
            } else {
              callback();
            }
          },
          trigger: 'blur'
        }
      ]
    };

    // 加载用户列表
    const loadUserList = async () => {
      state.loading = true;
      try {
        const response = await api.getUserList({
          page: state.queryParams.pageNum - 1, // 后端页码从0开始
          size: state.queryParams.pageSize,
          username: state.queryParams.username,
          phone: state.queryParams.phone,
          role: state.queryParams.role
        });

        if (response.data && response.data.success) {
          const data = response.data.data;
          // 处理角色显示文本
          state.userList = data.content.map(user => ({
            ...user,
            roleText: getRoleText(user.role)
          }));
          state.total = data.totalElements;
        } else {
          ElMessage.error(response.data.message || '获取用户列表失败');
        }
      } catch (error) {
        console.error('获取用户列表失败:', error);
        ElMessage.error('获取用户列表失败：' + (error.response?.data?.message || error.message || '服务器错误'));
      } finally {
        state.loading = false;
      }
    };

    // 搜索用户
    const searchUser = () => {
      state.queryParams.pageNum = 1;
      loadUserList();
    };

    // 重置查询
    const resetQuery = () => {
      state.queryParams.username = '';
      state.queryParams.phone = '';
      state.queryParams.role = '';
      state.queryParams.pageNum = 1;
      loadUserList();
    };

    // 处理每页显示条数变化
    const handleSizeChange = (pageSize) => {
      state.queryParams.pageSize = pageSize;
      loadUserList();
    };

    // 处理页码变化
    const handleCurrentChange = (pageNum) => {
      state.queryParams.pageNum = pageNum;
      loadUserList();
    };

    // 获取角色标签类型
    const getRoleTagType = (role) => {
      switch (role) {
        case 'ADMIN':
          return 'danger';
        case 'FARMER':
          return 'success';
        case 'DEALER':
          return 'warning';
        default:
          return 'info';
      }
    };

    // 获取角色文本
    const getRoleText = (role) => {
      switch (role) {
        case 'ADMIN':
          return '管理员';
        case 'FARMER':
          return '生产商';
        case 'DEALER':
          return '经销商';
        default:
          return '未知';
      }
    };

    // 处理用户状态变化
    const handleStatusChange = async (row) => {
      try {
        const response = await api.updateUserStatus(row.id, row.isActive);
        if (response.data && response.data.success) {
          ElMessage.success(`用户 ${row.username} 状态已${row.isActive ? '启用' : '禁用'}`);
        } else {
          // 状态更新失败，恢复UI状态
          row.isActive = !row.isActive;
          ElMessage.error(response.data.message || '更新状态失败');
        }
      } catch (error) {
        // 状态更新失败，恢复UI状态
        row.isActive = !row.isActive;
        console.error('更新用户状态失败:', error);
        ElMessage.error('更新用户状态失败：' + (error.response?.data?.message || error.message || '服务器错误'));
      }
    };

    // 打开添加对话框
    const openAddDialog = () => {
      state.dialogTitle = '添加用户';
      Object.assign(userForm, {
        id: null,
        username: '',
        realName: '',
        phone: '',
        email: '',
        role: '',
        isActive: true,
        password: ''
      });
      state.dialogVisible = true;

      nextTick(() => {
        userFormRef.value?.resetFields();
      });
    };

    // 处理编辑用户
    const handleEdit = async (row) => {
      state.loading = true;
      try {
        // 获取最新的用户数据
        const response = await api.getUserDetail(row.id);
        if (response.data && response.data.success) {
          const userData = response.data.data;
          state.dialogTitle = '编辑用户';
          Object.assign(userForm, {
            id: userData.id,
            username: userData.username,
            realName: userData.realName || '',
            phone: userData.phone || '',
            email: userData.email || '',
            role: userData.role,
            isActive: userData.isActive,
            password: ''
          });
          state.dialogVisible = true;
        } else {
          ElMessage.error(response.data.message || '获取用户详情失败');
        }
      } catch (error) {
        console.error('获取用户详情失败:', error);
        ElMessage.error('获取用户详情失败：' + (error.response?.data?.message || error.message || '服务器错误'));
      } finally {
        state.loading = false;
      }
    };

    // 处理删除用户
    const handleDelete = (row) => {
      ElMessageBox.confirm(`确认删除用户 ${row.username} 吗？此操作不可恢复！`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        state.loading = true;
        try {
          const response = await api.deleteUser(row.id);
          if (response.data && response.data.success) {
            ElMessage.success('删除成功');
            loadUserList(); // 重新加载列表
          } else {
            ElMessage.error(response.data.message || '删除失败');
          }
        } catch (error) {
          console.error('删除用户失败:', error);
          ElMessage.error('删除用户失败：' + (error.response?.data?.message || error.message || '服务器错误'));
        } finally {
          state.loading = false;
        }
      }).catch(() => {
        // 取消删除操作
      });
    };

    // 处理重置密码
    const handleResetPwd = (row) => {
      resetPwdForm.userId = row.id;
      resetPwdForm.username = row.username;
      resetPwdForm.newPassword = '';
      resetPwdForm.confirmPassword = '';
      state.resetPwdDialogVisible = true;

      nextTick(() => {
        resetPwdFormRef.value?.resetFields();
      });
    };

    // 提交重置密码
    const submitResetPwd = () => {
      resetPwdFormRef.value?.validate(async (valid) => {
        if (valid) {
          state.loading = true;
          try {
            const response = await api.resetPassword(resetPwdForm.userId, resetPwdForm.newPassword);
            if (response.data && response.data.success) {
              ElMessage.success(`用户 ${resetPwdForm.username} 密码重置成功`);
              state.resetPwdDialogVisible = false;
            } else {
              ElMessage.error(response.data.message || '密码重置失败');
            }
          } catch (error) {
            console.error('密码重置失败:', error);
            ElMessage.error('密码重置失败：' + (error.response?.data?.message || error.message || '服务器错误'));
          } finally {
            state.loading = false;
          }
        }
      });
    };

    // 重置表单
    const resetForm = () => {
      userFormRef.value?.resetFields();
    };

    // 提交表单
    const submitForm = () => {
      userFormRef.value?.validate(async (valid) => {
        if (valid) {
          state.loading = true;
          try {
            if (userForm.id === null) {
              // 添加用户
              const response = await api.addUser({
                username: userForm.username,
                realName: userForm.realName,
                phone: userForm.phone,
                email: userForm.email,
                role: userForm.role,
                isActive: userForm.isActive,
                password: userForm.password
              });

              if (response.data && response.data.success) {
                ElMessage.success('添加成功');
                state.dialogVisible = false;
                loadUserList(); // 重新加载列表
              } else {
                ElMessage.error(response.data.message || '添加失败');
              }
            } else {
              // 编辑用户
              const response = await api.updateUser(userForm.id, {
                realName: userForm.realName,
                phone: userForm.phone,
                email: userForm.email,
                role: userForm.role,
                isActive: userForm.isActive
              });

              if (response.data && response.data.success) {
                ElMessage.success('修改成功');
                state.dialogVisible = false;
                loadUserList(); // 重新加载列表
              } else {
                ElMessage.error(response.data.message || '修改失败');
              }
            }
          } catch (error) {
            console.error('保存用户失败:', error);
            ElMessage.error('保存用户失败：' + (error.response?.data?.message || error.message || '服务器错误'));
          } finally {
            state.loading = false;
          }
        }
      });
    };

    // 页面加载时获取用户列表
    onMounted(() => {
      loadUserList();
    });

    return {
      ...toRefs(state),
      userForm,
      userRules,
      resetPwdForm,
      resetPwdRules,
      userFormRef,
      resetPwdFormRef,
      loadUserList,
      searchUser,
      resetQuery,
      handleSizeChange,
      handleCurrentChange,
      getRoleTagType,
      handleStatusChange,
      openAddDialog,
      handleEdit,
      handleDelete,
      handleResetPwd,
      submitResetPwd,
      resetForm,
      submitForm,
      Search // 这里仍然需要导出Search，因为在模板中使用了 :icon="Search"
    };
  }
};
</script>

<style scoped>
.user-management-container {
  padding: 20px;
}

.content-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  //justify-content: space-between;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-tag) {
  text-align: center;
}
</style>
